#include <arpa/inet.h>
#include <assert.h>
#include <pthread.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

int cfd = -1;
int udpfd = -1;
struct sockaddr_in saddr;
void sockInit() {
    // socket
    cfd = socket(AF_INET, SOCK_STREAM, 0);
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(9999);
    inet_pton(AF_INET, "127.0.0.1", &saddr.sin_addr.s_addr);
    // connect
    int ret = connect(cfd, (struct sockaddr *)&saddr, sizeof(saddr));
    assert(!ret);
    cout << "连接成功" << endl;
}
void *udpLoop(void *) {
    // socket
    udpfd = socket(AF_INET, SOCK_DGRAM, 0);
    char sendBuf[128];
    while (true) {
        sprintf(sendBuf, "%d", cfd);
        int len = sendto(udpfd, sendBuf, strlen(sendBuf) + 1, 0,
                         (struct sockaddr *)&saddr, sizeof(saddr));
        if (len <= 0) {
            break;
        }
        sleep(1);
    }
}

int main() {
    sockInit();
    // create pthread
    pthread_t p1;
    pthread_create(&p1, NULL, udpLoop, NULL);
    while (true) {
        char buf[128] = "hello server";
        int len = send(cfd, buf, sizeof(buf), 0);
        sleep(3);
    }
    pthread_join(p1, NULL);
    return 0;
}